package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import persistence.exception.DAOException;
import persistence.util.JdbcUtil;

public class UserDAOJdbcImpl extends JdbcDAOBase implements UserDAO {

	private LibraryLocationDAO libraryLocationDAO;
	private RoleDAO roleDAO;
	
	public UserDAOJdbcImpl() {
		super();
	}
	
	public LibraryLocationDAO getLibraryLocationDAO() {
		return libraryLocationDAO;
	}

	public void setLibraryLocationDAO(LibraryLocationDAO libraryLocationDAO) {
		this.libraryLocationDAO = libraryLocationDAO;
	}	

	public RoleDAO getRoleDAO() {
		return roleDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}

	@Override
	public User find(int id) throws DAOException {
		return null;
	}
	
	@Override
	public User findByUsernameAndEncryptedPassword(String username, String password) throws DAOException {
		String sql = "SELECT id, username, passwort, ist_aktiv, bibliotheksstandorte_id FROM users WHERE username = ? AND passwort = ?";
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		User user = null;
		LibraryLocation location = null;
		List<Role> userRoles = null;
		
		try {
			con = getConProvider().getConnection();
			prepStmt = con.prepareStatement(sql);
			JdbcUtil.setParam(prepStmt, username, 1, Types.VARCHAR);
			JdbcUtil.setParam(prepStmt, password, 2, Types.VARCHAR);
//			prepStmt.setString(1, username);
//			prepStmt.setString(2, password);
			rs = prepStmt.executeQuery();
			
			if(rs.next()) {
				location = libraryLocationDAO.find(rs.getInt(5));
				int userId = rs.getInt(1);
				userRoles = roleDAO.findAllRolesForUser(userId);
				user = new User(userId, rs.getString(2), rs.getString(3), rs.getBoolean(4), location, userRoles);
			}
		}
		catch (SQLException se) {
			throw new DAOException("Problem when attempting to find User with username " + username + "and password " + password, se);
		}
		finally {
			JdbcUtil.cleanup(con, prepStmt, rs);
		}		
		return user;
	}

	@Override
	public List<User> findAllByName() throws DAOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update() throws DAOException {
		// TODO Auto-generated method stub

	}

	@Override
	public User create(int id, String username, String password, Boolean isActive, LibraryLocation libraryLocation) throws DAOException {
		// TODO Auto-generated method stub
		return null;
	}

}
